import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import legacy from "@vitejs/plugin-legacy";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import packageJson from "./package.json";

const __dirname = dirname(fileURLToPath(import.meta.url));

// https://vite.dev/config/
export default defineConfig({
  define: {
    // 全局变量
    __APP_VERSION__: JSON.stringify(packageJson.version),
    'import.meta.env.CUSTOM_VAR': JSON.stringify('custom value')
  },
  plugins: [
    react(),
    legacy({
      targets: ["defaults", "not IE 11"], // 兼容所有主流浏览器的最近两个版本，但明确排除 IE 11
    }),
  ],
  resolve: {
    alias: {
      "@": resolve(__dirname, "src"),
      "@components": resolve(__dirname, "src/components"),
    },
  },
  build: {
    rollupOptions: {
      input: {
        main: resolve(__dirname, "index.html"),
        about: resolve(__dirname, "about.html"),
        contact: resolve(__dirname, "contact.html"),
      },
      output: {
        manualChunks(id) {
          if (id.includes("node_modules")) {
            if (id.includes("react")) {
              return "react-vendor";
            }
            return "vendor";
          }
        },
        //  chunk 文件命名
        chunkFileNames: "assets/js/[name]-[hash].js",
        entryFileNames: "assets/js/[name]-[hash].js",
        assetFileNames: "assets/[ext]/[name]-[hash].[ext]",
      },
    },
  },
});
